<?php
/**
 * Created by PhpStorm.
 * User: xiaomage
 * Date: 2020/12/22
 * Time: 11:46
 */

namespace common\extra;


use common\ApiError;
use think\exception\ValidateException;

class Upload
{
    /**
     * @param null $file
     * @param array $config
     * @return bool|string
     */
    public static function image($file = null, $config = [])
    {
        if ($file === null) {
            $file = request()->file('file');
        }


        $size = $config['size'] ?? 1024*1024;
        $ext = $config['ext'] ?? 'jpg,jpeg,png,gif';

        try {
            /**
             * 验证大小依字节为单位
             *
             * 默认大小是1024*1024
             */
            validate(
                [
                    'image' => 'fileSize:' . $size . '|fileExt:' . $ext
                ]
            )->check(['image' => $file]);
        } catch (ValidateException $validateException) {
            ApiError::instance()->message($validateException->getMessage());
            return false;
        }

        $filename = \think\facade\Filesystem::disk('public')->putFile('img', $file);

        return str_replace('\\', '/', $filename);
    }

    /**
     * @param null $file
     * @return bool|string
     */
    public static function file($file = null)
    {
        if ($file === null) {
            $file = request()->file('file');
        }

        $filename = \think\facade\Filesystem::disk('public')->putFile('file', $file);

        return str_replace('\\', '/', $filename);
    }
}